#include "qNormativlista.h"
#include <QSqlQuery>
#include <QSqlRecord>
#include <QDesktopWidget>
#include <QMessageBox>


QNormativLista::QNormativLista(QWidget *parent)
	: QMyBaseFormWidget(parent)
{
	ui.setupUi(this);
	QDesktopWidget desk;
	QRect deskRect = desk.screenGeometry();
	ui.layoutWidget->setFixedWidth(deskRect.width() - 300);
	ui.layoutWidget->setFixedHeight(deskRect.height()-200);
	ui.tableView->setSelectionMode(QAbstractItemView::SingleSelection);
	ui.tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
	ui.tableView_2->setSelectionMode(QAbstractItemView::SingleSelection);
	ui.tableView_2->setSelectionBehavior(QAbstractItemView::SelectRows);
	ui.tableView->setSortingEnabled(true);
	connect(ui.tableView->horizontalHeader(),SIGNAL(sectionClicked(int)), ui.tableView, SLOT(sortByColumn(int)));
	ui.tableView_2->setSortingEnabled(true);
	connect(ui.tableView_2->horizontalHeader(),SIGNAL(sectionClicked(int)), ui.tableView_2, SLOT(sortByColumn(int)));
	connect(ui.lineEdit_6 ,SIGNAL(textChanged(const QString &)), this, SLOT(lineEditTextChanged(const QString &)));
    connect(ui.checkBox ,SIGNAL(stateChanged(int)), this, SLOT(checkBoxClicked(int)));
    connect(ui.pushButton_3 ,SIGNAL( clicked()), this, SLOT( pressDelete()));


	lista("%%%");
	m_selectedText = model->item(0, 0) ? model->item(0, 0)->text():"";
//	lista_detail(m_selectedText);
	ui.tableView->setFocus();
}

QNormativLista::~QNormativLista()
{
}


void QNormativLista::checkBoxClicked(int i)
{
lista(ui.lineEdit_6->text());
}


void QNormativLista::pressEscape()
{
    emit closeW();
}

void QNormativLista::lineEditTextChanged(const QString & text)
{
	lista(text);
}
void QNormativLista::lista(const QString& nameSearch)
{
    if (nameSearch.length() < 0)
    {
        ui.tableView->hide();
        return;
    }

    bool isNumeric = false;
    nameSearch.toInt(&isNumeric); 

    int r = 0;
    int c = 3;
    int fieldNo[3];
    QString country[3];
    int colWidth[] = {40, 180, 60};
    QString colName[] = {"id_proizvod", "artikal", "edm"};
    QString temp = "";
    if (ui.checkBox->isChecked())
    {
        if (isNumeric)
        {
            temp = "SELECT id_proizvod, artikal, edm, firma_id "
                "FROM proizvodi_sostav "
                "LEFT JOIN artikli ON proizvodi_sostav.id_proizvod = artikli.id "
                "WHERE id_proizvod = "+ nameSearch +" "
                "GROUP BY id_proizvod limit 100000";

        } 
        else
        {
            temp = "SELECT id_proizvod, artikal, edm, firma_id "
                "FROM proizvodi_sostav "
                "LEFT JOIN artikli ON proizvodi_sostav.id_proizvod = artikli.id "
                "WHERE artikal like '%"+ nameSearch +"%'"
                "GROUP BY id_proizvod limit 100000";

        }
    }
    else
    {
        if (isNumeric)
        {
            temp = "SELECT id_proizvod, artikal, edm, firma_id "
                "FROM proizvodi_sostav "
                "LEFT JOIN artikli ON proizvodi_sostav.id_proizvod = artikli.id "
                "WHERE id_proizvod = "+ nameSearch +" "
                "GROUP BY id_proizvod limit 20";
        } 
        else
        {
            temp = "SELECT id_proizvod, artikal, edm, firma_id "
                "FROM proizvodi_sostav "
                "LEFT JOIN artikli ON proizvodi_sostav.id_proizvod = artikli.id "
                "WHERE artikal like '%"+ nameSearch +"%'"
                "GROUP BY id_proizvod limit 20";
        }
    }

    QSqlQuery query(temp);
    model = new QStandardItemModel(r,c);
    model->setHeaderData( 0, Qt::Horizontal, trUtf8("Шифра"));
    model->setHeaderData( 1, Qt::Horizontal, trUtf8("Артикал"));
    model->setHeaderData( 2, Qt::Horizontal, trUtf8("Едм"));

    ui.tableView->setModel(model);
    header = new QHeaderView(Qt::Horizontal, this);
	header->setClickable(true);
    ui.tableView->setHorizontalHeader(header);
    header->show();
    int row = 0;
    while (query.next()) 
    {
        for (int i = 0; i < c; i++)
        {
            fieldNo[i] = query.record().indexOf(colName[i]);
            QStandardItem *item = new QStandardItem(query.value(fieldNo[i]).toString());
            item->setEditable(false);
            ui.tableView->setRowHeight(row, 18);
            ui.tableView->setColumnWidth(i, colWidth[i]);
            model->setItem(row, i, item);
        }
        row++;
    } 
    QItemSelectionModel *sm = ui.tableView->selectionModel();
    connect(sm, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
        this, SLOT(selectionChanged(QModelIndex,QModelIndex)));
    ui.tableView->show();
}
void QNormativLista::selectionChanged(QModelIndex modelX, QModelIndex modelY)
{
    int i = modelX.row();
	m_selectedText = model->item(i, 0) ? model->item(i, 0)->text():"";
	m_selectedText_name = model->item(i, 1) ? model->item(i, 1)->text():"";

    ui.lineEdit_2->setText(model->item(i, 1)->text());
    ui.lineEdit->setText(model->item(i, 2)->text());
//     ui.lineEdit_3->setText(model->item(i, 3)->text());
//     ui.lineEdit_4->setText(model->item(i, 4)->text());
//     ui.lineEdit_5->setText(model->item(i, 5)->text());

    lista_detail(m_selectedText);

}
void QNormativLista::lista_detail(const QString& nameSearch)
{
    QLocale loc;
    if (nameSearch.length() < 0)
    {
        ui.tableView_2->hide();
        return;
    }

    int r = 0;
    int c = 5;
    int fieldNo[5];
    QString country[5];
    int colWidth[] = {0, 40, 250, 70, 80};
    QString colName[] = {"id", "sifra", "artikal", "edm", "kolicina"};
    QString temp = 
		"SELECT artikli.id, artikli.sifra, artikli.artikal, artikli.edm, proizvodi_sostav.kolicina, proizvodi_sostav.firma_id "
		"FROM proizvodi_sostav "
		"LEFT JOIN artikli ON proizvodi_sostav.id_artikal = artikli.id  "
		"WHERE proizvodi_sostav.id_proizvod =";
	temp += m_selectedText;
    temp += "";
    QSqlQuery query(temp);

    model2 = new QStandardItemModel(r,c);
    model2->setHeaderData( 0, Qt::Horizontal, trUtf8("Ид."));
    model2->setHeaderData( 1, Qt::Horizontal, trUtf8("Шифра"));
    model2->setHeaderData( 2, Qt::Horizontal, trUtf8("Артикал"));
    model2->setHeaderData( 3, Qt::Horizontal, trUtf8("Едм."));
    model2->setHeaderData( 4, Qt::Horizontal, trUtf8("Количина"));
    ui.tableView_2->setModel(model2);
    header2 = new QHeaderView(Qt::Horizontal, this);
	header2->setClickable(true);
    ui.tableView_2->setHorizontalHeader(header2);
    header2->show();
    int row = 0;
    while (query.next()) 
    {
        QBrush newBrush;

        if (query.value(5).toInt() == 1)
        {
            newBrush.setColor(Qt::darkRed);
        }
        else
        {
            newBrush.setColor(Qt::black);
        }

        for (int i = 0; i < c; i++)
        {
             fieldNo[i] = query.record().indexOf(colName[i]);
//             QStandardItem *item = new QStandardItem(query.value(fieldNo[i]).toString());
            QStandardItem *item = NULL;
            QString temp = query.value(fieldNo[i]).toString();
            if (i > 3)
            {
                temp =  loc.toString(temp.toFloat(), 'f', 2);
                item = new QStandardItem(temp);
                item->setTextAlignment(Qt::AlignRight);
            }
            else
            {
                item = new QStandardItem(temp);
                item->setTextAlignment(Qt::AlignLeft);
            }
            item->setForeground(newBrush);
            item->setEditable(false);
            ui.tableView_2->setRowHeight(row, 18);
            ui.tableView_2->setColumnWidth(i, colWidth[i]);
            model2->setItem(row, i, item);
        }
        row++;
    } 
    ui.tableView_2->show();
}

void QNormativLista::deleteDok(int idDok)
{
    QSqlQuery query;
    query.clear();
    query.prepare(
        "delete from magacin where dok_tip = 40 and dok_id = :a"
        );
    query.bindValue(":a", idDok);	
    query.exec();
}
void QNormativLista::on_pushButton_clicked()
{
    emit procF2();
}
void QNormativLista::on_pushButton_2_clicked()
{
    emit procF3();
}

void QNormativLista::on_pushButton_4_clicked()
{
    emit procF6();
}

QStringList QNormativLista::geInfo()
{
    QStringList info;
    info.clear();
    info << ui.lineEdit_3->text() << ui.lineEdit_4->text() << ui.lineEdit_5->text() << ui.lineEdit->text()<< ui.lineEdit_2->text(); 
    return info;
}

void QNormativLista::pressReturn()
{
	if (ui.lineEdit->hasFocus())
	{
		ui.tableView->setFocus();
	}
	else if (ui.tableView->hasFocus())
	{
		emit sNormativToNalog(m_selectedText, m_selectedText_name);	
	}
}

void QNormativLista::pressDelete()
{
    QMessageBox msgBox;
    msgBox.setText(trUtf8("Нормативот ќе биде избришан!!!"));
    msgBox.setInformativeText(trUtf8("Дали сакате да биде избришан?"));
    msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
    msgBox.setDefaultButton(QMessageBox::No);
    int ret = msgBox.exec();
    if (ret == QMessageBox::Yes) 
    {
        // Save was clicked
        int selectedID = getSelectedId();
        QSqlQuery query;
        query.clear();
        query.prepare(
            "delete from proizvodi_sostav where id_proizvod = :a" );
        query.bindValue(":a", selectedID);	
        query.exec();
        // Refresh
        lista(ui.lineEdit_6->text());
    }   
}